package com.qingerai.blefastdemo;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.qingerai.blefastdemo.databinding.ActivityMainBinding;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private static final int WIRTE = 1;
    private static final int NOTIFY = 2;
    private ActivityMainBinding mainBinding;
    private BleManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_main);
        mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        initBle();

        initView();


    }

    private String TAG = "klxq";
    BleDevice bleDevice1 = null;

    private void initView() {


        mainBinding.tvSearch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                try {
                    if (manager != null) {
                        manager.disconnect(bleDevice1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG, "onClick: -----------" + e.getMessage());
                }
            }
        });


        mainBinding.tvSearch3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sendMsg();
            }
        });


        mainBinding.tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // BleManager.getInstance().disconnect();
                //开启连接 C3:FE:BD:B7:D1:1E  徐洋洋   CF:F3:B4:EF:1D:01 李林    E4:F7:94:11:36:B6余家林
                BleManager.getInstance().connect("C3:FE:BD:B7:D1:1E", new BleGattCallback() {
                    @Override
                    public void onStartConnect() {

                        Log.e(TAG, "onStartConnect: --------");
                    }

                    @Override
                    public void onConnectFail(BleDevice bleDevice, BleException e) {

                        Log.e(TAG, "onConnectFail: " + e.getDescription());
                    }

                    @Override
                    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt bluetoothGatt, int i) {

//                        Log.e(TAG, "onConnectSuccess: " + bleDevice.getName() + "---------i:" + i);
                        bleDevice1 = bleDevice;

                        //连接成功后，调用：设置更新监听

                        //优先处理时间问题 时间设置为手机时间


                        //movement.setDateTime(calendar,)


                        BluetoothGatt gatt = BleManager.getInstance().getBluetoothGatt(bleDevice);

                        List<BluetoothGattService> serviceList = bluetoothGatt.getServices();
                        for (BluetoothGattService service : serviceList) {
                            UUID uuid_service = service.getUuid();
                            //uuid_service = uuid_service.toString();
                            Log.e(TAG, "onConnectSuccess: ---uuid_service----:" + uuid_service);
                            List<BluetoothGattCharacteristic> characteristicList = service.getCharacteristics();
                            for (BluetoothGattCharacteristic characteristic : characteristicList) {
                                UUID uuid_chara = characteristic.getUuid();
                                String uuStr = uuid_chara.toString();
                                Log.e(TAG, "--uuStr---:" + uuStr);
                                if (uuStr.contains("fff1")) {
                                    Log.e(TAG, "onConnectSuccess: -------fff1写-----" + uuStr);
                                    writeMsg(bleDevice, uuid_service, uuid_chara);
                                } else if (uuStr.contains("fff2")) {
                                    Log.e(TAG, "onConnectSuccess: -------fff2 --通知---" + uuStr);
                                    setNotify(bleDevice, uuid_service, uuid_chara);
                                }
                            }
                        }

                    }

                    @Override
                    public void onDisConnected(boolean b, BleDevice bleDevice, BluetoothGatt bluetoothGatt, int i) {

                    }
                });
            }
        });
    }


    public class DeviceInfo {

        private String uuid_service;
        private String uuid_chara;

        public DeviceInfo() {
        }

        public DeviceInfo(String uuid_service, String uuid_chara) {
            this.uuid_service = uuid_service;
            this.uuid_chara = uuid_chara;
        }

        public String getUuid_service() {
            return uuid_service;
        }

        public void setUuid_service(String uuid_service) {
            this.uuid_service = uuid_service;
        }

        public String getUuid_chara() {
            return uuid_chara;
        }

        public void setUuid_chara(String uuid_chara) {
            this.uuid_chara = uuid_chara;
        }
    }

    private void setNotify(BleDevice bleDevice, UUID uuid_service, UUID uuid_chara) {


        Log.e(TAG, "setNotify: --------------------" + uuid_service + "===========" + uuid_chara);

        manager.notify(bleDevice, uuid_service.toString(), uuid_chara.toString(), new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                Log.e(TAG, "onNotifySuccess: ");
            }

            @Override
            public void onNotifyFailure(BleException e) {
                Log.e(TAG, "onNotifyFailure: " + e.getDescription());
            }

            @Override
            public void onCharacteristicChanged(byte[] bytes) {

                //  Log.e(TAG, "onCharacteristicChanged: ---- 打开通知后，设备发过来的数据将在这里出现--- indicate--" + "--data-" + Arrays.toString(bytes)  + bleDevice.getMac());
                Log.e(TAG, "onCharacteristicChanged: ---- 打开通知后，设备发过来的数据将在这里出现--- indicate--" + "--data-" + FormatUtils.bytes2HexString(bytes) + bleDevice.getMac());
                // Log.e(TAG, "onCharacteristicChanged: ---- 打开通知后，设备发过来的数据将在这里出现--- indicate--" + "--data-" +new String(bytes));
                String s = HexUtil.byteToHex(bytes[0]);
                if (s.equals("90")) {
                    int aByte = Integer.valueOf(HexUtil.byteToHex(bytes[2]));
//                    for (int i = 0; i < aByte; i++) {
//                        for (int j = 0; j < 8; j++) {
//                            //0x17是获取心率的协议
//                            byte[] send = new byte[3];
//                            send[0] = 0x17;
//                            send[1] = (byte) i;
//                            send[2] = (byte) (j * 3);
//                            sendMsg(send);
//
//
//                        }
//                    }
//                    for (int i = 0; i < aByte; i++) {
//                        for (int j = 0; j < 8; j++) {
//
//                            //0x18是获取血氧的协议
//                            byte[] send2 = new byte[3];
//                            send2[0] = 0x18;
//                            send2[1] = (byte) i;
//                            send2[2] = (byte) (j * 3);
//                            sendMsg(send2);
//
//
//                        }
//                    }


                    for (int i = 0; i < aByte; i++) {

                        for (int j = 0; j < 24; j++) {

//                            // 0x19是获取体温的协议
//                            // 0x1c是获取RRI协议
//
                            byte[] send3 = new byte[3];
                            send3[0] = 0x19;
                            send3[1] = (byte) i;
                            send3[2] = (byte) (j);
                            sendMsg(send3);
                        }
                    }


                    for (int i = 0; i < aByte; i++) {

                        for (int j = 0; j < 24; j++) {

//                            // 0x19是获取体温的协议
//                            // 0x1c是获取RRI协议

                            byte[] send4 = new byte[3];
                            send4[0] = 0x1c;
                            send4[1] = (byte) i;
                            send4[2] = (byte) (j);
                            sendMsg(send4);

                        }
                    }
                } else if (s.equals("97")) {
                    //发送0x17，i，j*3； 每次获取3小时数据 0x17是获取心率的协议
                    //接收：0x97, YY1,YY2,MM,DD,HH,HR1-1,HR1-2,HR1-3,HR1-4,,,,,HR3-3,HR3-4
                    //YY1,YY2,MM,DD: 当前获取到心率数据的年月日
                    //HH：当前获取到心率的起始小时 比如8点为起始时间
                    //HR1-1表示从起始时间起，比如8点为起始时间，第一个15分钟也就是8点15采集的	心率均值。数据一直到HR3-4，也就是10点最后一个15分钟采集的数据
                    Log.e(TAG, "onCharacteristicChanged: ---97- --" + "--data-" + FormatUtils.bytes2HexString(bytes));

                } else if (s.equals("98")) {

                    //发送0x18，i，j*3； 每次获取3小时数据 0x18是获取血氧的协议
                    //接收：0x98, YY1,YY2,MM,DD,HH,SPO1-1,SPO1-2,SPO1-3,SPO1-4,,,,,SPO3-3,SPO3-4
                    //YY1,YY2,MM,DD: 当前获取到血氧数据的年月日
                    //HH：当前获取到血氧的起始小时 比如8点为起始时间
                    //SPO1-1表示从起始时间起，比如8点为起始时间，第一个15分钟也就是8点15采集的血氧均值。数据一直到SPO3-4，也就是10点最后一个15分钟采集的数据。
                    Log.e(TAG, "onCharacteristicChanged: ---98- --" + "--data-" + FormatUtils.bytes2HexString(bytes));
                }

                else if (s.equals("99")) {
                    //发送0x19，i，j； 每次获取1小时数据 0x19是获取体温的协议
                    //接收：0x99, YY1,YY2,MM,DD,HH, TPH1,TPl1,TPH2,TPL2,,,,  3e55
                    //YY1,YY2,MM,DD: 当前获取到体温数据的年月日
                    //HH：当前获取到体温的起始小时
                    //TPH1为第一个体温数据的高8位，TPL1为第一个体温数据的低8位，以此类推。
                    //体温数据比如为3650，表示36.50摄氏度。
                    Log.e(TAG, "onCharacteristicChanged: ---98- --" + "--data-" + FormatUtils.bytes2HexString(bytes));
                } else if (s.equals("")) {
                    //发送0x1C，i，j； 每次获取1小时数据 0x1C是获取RRI的协议
                    //接收：0x99, YY1,YY2,MM,DD,HH, RRI1-H,RRI1-L,,,,
                    //YY1,YY2,MM,DD: 当前获取到RRI数据的年月日
                    //HH：当前获取到RRI的起始小时
                    //RRI1-H表示第一个rri的高8位，RRI1-L表示第一个rri的低8位。以此类推。
                    Log.e(TAG, "onCharacteristicChanged: ---98- --" + "--data-" + FormatUtils.bytes2HexString(bytes));
                }

            }
        });

//        manager.indicate(
//                bleDevice,
//                uuid_service.toString(),
//                uuid_chara.toString(),
//                new BleIndicateCallback() {
//                    @Override
//                    public void onIndicateSuccess() {
//                        // 打开通知操作成功
//                        Message message = Message.obtain();
//                        message.what = NOTIFY;
//                        DeviceInfo info = new DeviceInfo(uuid_service.toString(), uuid_chara.toString());
//                        message.obj = info;
//                        handler.sendMessage(message);
//                        Log.e(TAG, "onIndicateSuccess: indicate 打开通知操作成功" + uuid_chara.toString());
//                    }
//
//                    @Override
//                    public void onIndicateFailure(BleException exception) {
//                        // 打开通知操作失败
//
//                        Log.e(TAG, "onIndicateFailure:   indicate   打开通知操作失败");
//                    }
//
//                    @Override
//                    public void onCharacteristicChanged(byte[] data) {
//                        // 打开通知后，设备发过来的数据将在这里出现
//                        Log.e(TAG, "onCharacteristicChanged: ---- 打开通知后，设备发过来的数据将在这里出现--- indicate--" + "--data-" + new String(data));
//
//
//                    }
//                });
    }

    //使用1字节就可以表示b
    public static String numToHex8(int b) {
        return String.format("%02x", b);//2表示需要两个16进行数
    }

    private void sendMsg(byte[] send) {

        if (bleDevice1 != null) {
            manager.write(
                    bleDevice1,
                    uuid_service,
                    uuid_characteristic_write,
                    send,
                    new BleWriteCallback() {
                        @Override
                        public void onWriteSuccess(int current, int total, byte[] justWrite) {
                            // 发送数据到设备成功（分包发送的情况下，可以通过方法中返回的参数可以查看发送进度）
                            //String s = new String(justWrite);
                            Log.e(TAG, "onWriteSuccess: ---------发送指令:" + FormatUtils.bytes2HexString(justWrite));
                            //Log.e(TAG, "onWriteSuccess: ------999-----" + Arrays.toString(justWrite));
                        }

                        @Override
                        public void onWriteFailure(BleException exception) {
                            // 发送数据到设备失败
                            Log.e(TAG, "onWriteFailure: 发送数据到设备失败" + exception.getDescription());
                        }
                    });
        }


    }

    String uuid_service = null;
    String uuid_characteristic_write = "";
    String uuid_characteristic_notify = "";
    String uuid_characteristic_read = "";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == WIRTE) {

                DeviceInfo info = (DeviceInfo) msg.obj;
                uuid_service = info.getUuid_service();
                uuid_characteristic_write = info.getUuid_chara();
            } else if (msg.what == NOTIFY) {
                DeviceInfo info = (DeviceInfo) msg.obj;
                uuid_service = info.getUuid_service();
                uuid_characteristic_read = info.getUuid_chara();
            }
        }
    };

    private void writeMsg(BleDevice bleDevice, UUID uuid_service, UUID uuid_chara) {

        //  byte[] bytes = "0x10".getBytes();
        //this.uuid_service = uuid_service.toString();

        byte[] data = new byte[1];
        data[0] = 0x10;


        manager.write(
                bleDevice,
                uuid_service.toString(), uuid_chara.toString()
                ,
                data,
                new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        //  justWrite 为指令内容


                        Message message = Message.obtain();
                        message.what = WIRTE;
                        DeviceInfo info = new DeviceInfo(uuid_service.toString(), uuid_chara.toString());
                        message.obj = info;
                        handler.sendMessage(message);

                        Log.e(TAG, "onWriteSuccess: 为指令内容" + justWrite.toString());

                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        // 指令发送失败
                        Log.e(TAG, exception.getDescription());
                    }
                });
    }


    private void sendMsg() {

        byte[] data = new byte[1];
        data[0] = 0x10;

        if (bleDevice1 != null) {
            manager.write(
                    bleDevice1,
                    uuid_service,
                    uuid_characteristic_write,
                    data,
                    new BleWriteCallback() {
                        @Override
                        public void onWriteSuccess(int current, int total, byte[] justWrite) {
                            // 发送数据到设备成功（分包发送的情况下，可以通过方法中返回的参数可以查看发送进度）

                            String s = new String(justWrite);
                            Log.e(TAG, "onWriteSuccess: ------666-----" + Arrays.toString(justWrite));
                        }

                        @Override
                        public void onWriteFailure(BleException exception) {
                            // 发送数据到设备失败
                            Log.e(TAG, "onWriteFailure: 发送数据到设备失败");
                        }
                    });
        }


    }


    /**
     * 初始化蓝牙
     */
    private void initBle() {

        BleManager.getInstance().init(getApplication());
        manager = BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 10000)
                .setOperateTimeout(10000);


        boolean supportBle = BleManager.getInstance().isSupportBle();

        if (supportBle) {

        }

        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                //  .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
                //   .setDeviceName(true, names)         // 只扫描指定广播名的设备，可选
                //  .setDeviceMac(mac)                  // 只扫描指定mac的设备，可选
                //   .setAutoConnect(isAutoConnect)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒
                .build();
        manager.initScanRule(scanRuleConfig);


    }
}